<!-- <template>
  <div id="app">
      <input type="file" @change="handleChange"/>
      <button @click="handleUpload()">上传</button>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import _, { random } from 'lodash'
import { randomId } from "./util/IdUtil";

 // 文件分片定义
type FileChunks = {
  file:File;
  chunks: {
    start: number;
    end: number;
  }[];
}
export default class Home extends Vue {
  // 是否全部片段已上传完成
  allChunksUploded= false;
  // 文件上传容器
  container:{file:null | File} = {file: null}
  // 文件快
  chunkSize = 10 * 1024 * 1024;

  // 上传进度
  uploadProcess = 0;

  handleChange(e:Event) {
    const files = (e.target as any).files;
    if(!files || files.length === 0) return;
    this.container.file = files[0];
    // 设置上传状态
    this.allChunksUploded = false;
  }

  // 上传
  handleUpload() {
    const fileChunks  = this.makeChunks(this.container.file!);
    const allChunksUploadStatus =  _.fill(
      new Array(fileChunks.chunks.length),
      false
    );
    // 重置上传进度
    this.allChunksUploded = false;
    this.uploadProcess = 0;
    // 计算上传进度
    const calUploadProcess = ():number=>{
       let uploadedCount = 0;
      _.each(allChunksUploadStatus,item=>{
        if(item) uploadedCount ++;
      })
      return new Number(((uploadedCount *100) / allChunksUploadStatus.length ).toFixed(0)).valueOf();
    }
    // 生成uid 传递给后端 后端根据uid对子文件块进行合并
     const fileUid = randomId();
    fileChunks.chunks.forEach(
      (chunk: { start: number; end: number }, index: number) => {
        const formData = new FormData();
        formData.append("index", index + "");
        formData.append("chunk", fileChunks.file.slice(chunk.start, chunk.end));
        formData.append("name", fileChunks.file.name);
        formData.append("chunksLength", fileChunks.chunks.length + "");
        formData.append("uid", fileUid);
        // 以下调用接口 不太重要 可暂时忽略这个地方
        Axios.post<ChunkUploadResult>("/api/fileupload", formData)
          .catch((reason) => console.error(`error: ${JSON.stringify(reason)}`))
          .then((res) => {
            if (typeof res === "object") {
              const data = res.data;
              if (isChunkUploadResult(data)) {
                if (data.status) {
                  allChunksUploadStatus[index] = true;
                  // 更新上传百分比
                  this.uploadProcess = calUploadProcess();
                  // 更新上传状态
                  if (this.uploadProcess === 100) this.allChunksUploaded = true;
                }
              }
            }
          });
      }
    );
  }

  makeChunks(file:File):FileChunks {
    const fileChunks:FileChunks = {
      file,
      chunks: []
    }
    //  上传的文件小于需要分片的文件大小
    if(file.size < this.chunkSize) {
      fileChunks.chunks.push({start: 0,end:file.size})
      return fileChunks;
    }
    let chunksLength;
    if(file.size % this.chunkSize === 0) {
      chunksLength = Math.floor(file.size / this.chunkSize);
    }else {
      chunksLength = Math.floor(file.size / this.chunkSize) + 1;
    }
    let leftSize = file.size;
    while(leftSize > 0) {
      const start = fileChunks.chunks.length * this.chunkSize;
      const end = start + this.chunkSize >= file.size ? file.size :start + this.chunkSize
      leftSize -= end - start;
      fileChunks.chunks.push({start,end});
    }
    
    return fileChunks;
  }
}
</script> -->
